package net.ncraft.mc.ezframework.core.ezbatis;

import lombok.Getter;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class DefaultSqlSession implements SqlSession{

    @Getter
    private final Map<Class<?>, Object> MAPPERS_PROXY = new HashMap<>();

    private final Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        init();
    }

    @Override
    public <T> T getMapper(Class<T> mapperClass) {
        return (T) MAPPERS_PROXY.get(mapperClass);
    }

    private void init() {
        configuration.getMappers().forEach(mapper -> {
            Object o = Proxy.newProxyInstance(mapper.getClassLoader(), new Class[]{mapper}, new MapperProxy(configuration.getEnvironment()));
            MAPPERS_PROXY.put(mapper, o);
        });
    }
}
